package com.ming.ksdstate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ming.ksdstate.entity.State;
import com.ming.ksdstate.entity.StateDetail;
import com.ming.ksdstate.service.detail.StateDetailService;
import com.ming.ksdstate.service.state.StateService;
import com.ming.ksdstate.service.stateuser.StateUserDetailService;
import com.ming.ksdstate.vo.R;
import com.ming.ksdstate.vo.StateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author -Ming
 * @ClassName SateController
 * @CreateTime 2021-10-10
 * @Description TODO
 **/
@Controller
@RequestMapping("/state")
public class SateController {

    @Autowired
    private StateService stateService;

//    @GetMapping("/list")
//    public R findStates(){
//        QueryWrapper<State> queryWrapper = new QueryWrapper<>();
////        return stateService.list(queryWrapper);
//        return R.ok().data("results",stateService.list(queryWrapper));
//    }

    @Autowired
    private StateDetailService stateDetailService;
    @Autowired
    private StateUserDetailService stateUserDetailService;

    /*
     * @Description 根据id跳转到制定的统计明细页面
     **/
    @GetMapping("/state/{id}")
    public String findStates(@PathVariable("id") Integer id, ModelMap modelMap) {
        // 1:根据id查询统计是否存在
        State state = stateService.getById(id);
        if (state != null) {
            // 2：如果存在就进入页面
            modelMap.put("id", id);
            return "state/detail";
        }
        // 3: 如果不存在就进入到错误页面，（后台讲解统一异常处理和错误处理）
        return "redirect:/error";
    }


    /*
     * @Description 根据stateid想查询统计和统计明细
     **/
    @GetMapping("/state/detail")
    @ResponseBody
    public R getStateDetail(Integer stateid) {
        if (StringUtils.isEmpty(stateid)) return R.error().code(601).message("没有找到对应主题");
        //1 :根据stateid查询统计
        State state = stateService.getById(stateid);
        if (state == null) return R.error().code(601).message("没有找到对应主题");
        //2 :根据stateid查询统计明细
        QueryWrapper<StateDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stateid", stateid);
        List<StateDetail> stateDetaiList = stateDetailService.list(queryWrapper);
        //3 :把state对象和statedetail组装到vo对象
        StateVo stateVo = new StateVo();
        BeanUtils.copyProperties(state, stateVo);
        stateVo.setStateDetailList(stateDetaiList);
        //4 :然后把vo用 R统一返回出去
        return R.ok().data("stateVo", stateVo);
    }



}
